import util from "./util";
import api from "./api";
const app = getApp();



function getQRCode(options, callback) {
    lkRequest({
        url: url.urls.getQRCode,
        method: 'POST',
        params: options || null,
        contentType: 'application/json;charset=utf-8'
    },(res)=>{
        console.log(res)
        callback(res)
    },(err)=>{
        wx.showToast({
            title: err.data.message,
            icon: 'none',
            duration: 3000
        })
    })

}

function isRight(dataItems){
        let term = wx.getStorageSync("term");
        let physiqueName = wx.getStorageSync("physiqueName");
        let termNow = JSON.stringify({"value": term});
        let physiqueNameNow = JSON.stringify({"value": physiqueName});
        let physiqueList = [];
        let termList = [];
        let isRight = [];
        if (dataItems.length > 0) {
            let items = dataItems;
            console.log(items)
            for (let i = 0; i < items.length; i++) {
                if (items[i].cateringDishes.length > 0) {
                    let physiqueItem = items[i].cateringDishes[0].physique;
                    physiqueList.push(physiqueItem);
                } else {
                    physiqueList.push("[]");
                }

                if (items[i].cateringDishes.length > 0) {
                    let termItem = items[i].cateringDishes[0].term;
                    termList.push(termItem);
                } else {
                    termList.push("[]");
                }
                if ((physiqueList[i].indexOf(physiqueNameNow) > -1) && (termList[i].indexOf(termNow) > -1)) {
                    isRight.push(true);
                } else {
                    isRight.push(false);
                }
            }
            return  {
                isRight
            }
        }
    }



 const setShareImg = (options) => {
    return new Promise((resolve, reject) => {
        let {id, bg, codeImg} = options;
        let physiqueName = wx.getStorageSync("physiqueName") || '';
        let dishList = wx.getStorageSync("dishList") || '';
            const ctx = wx.createCanvasContext(id);
            // 绘制背景图片
            ctx.drawImage(bg, 0, 0, 320, 507);
            ctx.drawImage(codeImg, 240,425,62,62);


            if(physiqueName && dishList) {
                ctx.setFontSize(12);
                ctx.fillStyle = '#fff';
                ctx.fillText('我是', 20, 372);

                ctx.setFontSize(12);
                ctx.fillStyle = '#1AA7C3';
                ctx.fillText(physiqueName, 48, 372);

                ctx.setFontSize(12);
                ctx.fillStyle = '#fff';
                ctx.fillText(`，${app.globalData.dpd.tableInfo.tablename}适合我的体质的菜品有：`, 90, 372);

                ctx.setFontSize(11);
                ctx.fillStyle = '#fff';
                ctx.fillText(dishList, 20, 392);

            } else {

                ctx.setFontSize(12);
                ctx.fillStyle = '#fff';
                ctx.fillText('中医素有"', 20, 372);

                ctx.setFontSize(12);
                ctx.fillStyle = '#1AA7C3';
                ctx.fillText('药食同源', 76, 372);

                ctx.setFontSize(12);
                ctx.fillStyle = '#fff';
                ctx.fillText('"之说，体质通过长期的', 130, 372);

                ctx.setFontSize(11);
                ctx.fillStyle = '#fff';
                ctx.fillText('饮食调理是可以得到改善的。', 20, 392);

            }




            ctx.setFontSize(12);
            ctx.fillStyle = '#fff';
            ctx.fillText('赶快扫码', 20, 413);

            ctx.setFontSize(12);
            ctx.fillStyle = '#3CB371';
            ctx.fillText('检测体质', 71, 413);

            ctx.setFontSize(12);
            ctx.fillStyle = '#fff';
            ctx.fillText('，看看你适合吃哪些菜品吧！' , 125, 413);

            ctx.clip();
            ctx.draw(true, () => {
                console.log(options);
                wx.canvasToTempFilePath({
                    width:320,
                    height:507,
                    destWidth: 640,
                    destHeight:1014,
                    canvasId: id,
                    fileType: 'jpg',
                    quality: 1,
                    success: (res) => {
                        resolve({
                            img: res.tempFilePath
                        })
                    },
                    fail: (e) => {
                        console.error('draw方法生成图片错误', e);
                        reject(e)
                    }
                })
            })
        })

    };



const init = (id, options = {}) => {
    let {
        bg
    } = options

    // 缓存网络图片到本地
    let promise1 = new Promise(function (resolve, reject) {
        let codeImg = util.createMiniQrCode(`/package-dpd/card/card?catid=${app.globalData.dpd.tableInfo.catid}`);
        wx.getImageInfo({
            src: codeImg,
            success: function (res) {
                // console.log(res)
                resolve(res);
            },
            fail: e => {
                console.error('缓存二维码出现错误', e)
                reject(e)
            }
        })
    });
    let promise2 = new Promise(function (resolve, reject) {
        wx.getImageInfo({
            src: bg,
            success: function (res) {
                // console.log(res)
                resolve(res)
            },
            fail: e => {
                console.error('缓存背景图片出现错误', e)
                reject(e)
            }
        })
    })
    let promiseAll = [promise1, promise2];
    return new Promise((reslove, reject) => {
        Promise.all(promiseAll).then(res => {
            let options = {
                id,
                codeImg: res[0].path,
                bg: res[1].path,
            }
            setShareImg(options).then(res => {
                reslove(res)
            }).catch(e => {
                reject(e)
            })
        }).catch(e => {
            console.error(e)
            reject(e)
        })
    })
}

const dpdConfigApi = (data) => {
    if (data === '0') {
        return {
            getOrder: '/api/wechatxcx/catering/sys/order/queryCatInfo/',  // 获取订单
            saveOrder: '/api/wechatxcx/catering/sys/order/saveOrder', // 点餐
            endChoiceOrder: '/api/wechatxcx/catering/sys/order/endChoiceOrder', // 下单
            palceOrder: '/api/wechatxcx/catering/sys/order/querySysPlacedOrder', // 已下单列表
            payOrder: '/api/wechatxcx/catering/sys/order/payOrder' // 支付接口
        }

    } else if (data === '1') {
        return {
            getOrder: '/api/wechatxcx/catering/order/queryCatInfo/',
            saveOrder: '/api/wechatxcx/catering/order/saveOrder',
            endChoiceOrder: '/api/wechatxcx/catering/order/endChoiceOrder',
            palceOrder: '/api/wechatxcx/catering/order/queryNcrOrderDetails',
            payOrder: '/api/wechatxcx/catering/order/payOrder'
        }

    }
}


// 是否适合体质与节气
// const isFit = (bodyData, storageName) => {
//     let nowData =  wx.getStorageSync(storageName) || '';
//     let newArray = [];
//     if(nowData && bodyData.length >0 ) {
//         newArray = bodyData.filter((item) => {
//             return item.value === nowData
//         });
//         if (newArray.length > 0) {
//             return true
//         } else {
//             return false
//         }
//     }
//     return false
// }

const isFit = (bodyData, name) => {
    if (typeof bodyData === 'string' && bodyData.indexOf(name) > -1) {
        return true
    } else {
        return false
    }

}

const getJieQi = (yyyy=new Date().getFullYear(), mm=new Date().getMonth() , dd=new Date().getDate()) => {
    var sTermInfo = new Array(0, 21208, 42467, 63836, 85337, 107014, 128867, 150921, 173149, 195551, 218072, 240693, 263343, 285989, 308563, 331033, 353350, 375494, 397447, 419210, 440795, 462224, 483532, 504758);
    var solarTerm = new Array("小寒", "大寒", "立春", "雨水", "惊蛰", "春分", "清明", "谷雨", "立夏", "小满", "芒种", "夏至", "小暑", "大暑", "立秋", "处暑", "白露", "秋分", "寒露", "霜降", "立冬", "小雪", "大雪", "冬至");
    var solarTerms = "";
    while (solarTerms == "") {
        var tmp1 = new Date((31556925974.7 * (yyyy - 1900) + sTermInfo[mm * 2 + 1] * 60000) + Date.UTC(1900, 0, 6, 2, 5));
        var tmp2 = tmp1.getUTCDate();
        if (tmp2 == dd) solarTerms = solarTerm[mm * 2 + 1];
        tmp1 = new Date((31556925974.7 * (yyyy - 1900) + sTermInfo[mm * 2] * 60000) + Date.UTC(1900, 0, 6, 2, 5));
        tmp2 = tmp1.getUTCDate(); if (tmp2 == dd) solarTerms = solarTerm[mm * 2];
        if (dd > 1) {
            dd = dd - 1;
        } else {
            mm = mm - 1;
            if (mm < 0) {
                yyyy = yyyy - 1; mm = 11;
            }
            dd = 31;
        }
    }
    wx.setStorageSync('term',solarTerms);

    return solarTerms
}


// 获取相应的口味
const getTaste = (data) => {
    if (data) {
        let tasteArray = JSON.parse(data);
        let tasteItem=[];
        let tasteDes = ['非清真' , '清真', '咸口', '辣口', '酸甜', '甜口', '微甜', '鲜香', '麻辣', '酸辣', '微辣', '咸甜', '咸鲜', '咸香', '甜辣',
            '麻香', '爽口', '干香', '香甜',undefined, '真咸辣', '香辣', '咸微甜', '甜香', '酥脆', '咸鲜香', '酱香', '蚝油', '原味', '浓香', '酱香咸甜', '香麻', '葱香原味'];
        for(let i=0;i<tasteArray.length; i++){
            let j = parseInt(tasteArray[i].value);
            if(tasteDes[j]) {
                tasteItem.push(tasteDes[j])
            }
        }
        return tasteItem
    } else {
        return []
    }

}

/**
 * 获取用户体质
 */
const getLastExamDetails = () =>{
    return new Promise ((resolve, reject) => {
        api.post('/app/exam/getLastExamDetails', {
            head: {
                "firstresult": 0,
                "maxresults": 2147483647,
                "bodytype": "flat"
            },
            data: {
                "examSpace": "PD"
            }
        }).then(res => {
            if (res.length > 0) {
                // wx.setStorageSync('physiqueName',res[0].exam_diseasename);
                // wx.setStorageSync('physiqueCode',res[0].exam_diseasecode);
                resolve(
                    {
                        phyName:res[0].exam_diseasename,
                        phyCode:res[0].exam_diseasecode

                    }
                )
            }

        }).catch(err => {
            reject(err);
            console.log(err)
        })

    })


}

const uuid = () => {
    const time = new Date().getTime();
    let timeLen = time.toString(16).length;
    let nextCode = ''
    for (let i = 0; i < (32 - timeLen); i++) {
        nextCode += parseInt(Math.random() * 15).toString(16);
    }
    let uuid = time.toString(16) + nextCode;
    return uuid;
}

// m-n 随机数
const rand = (m,n) => {
    m = m || 1;
    n = n || 5;
    return m + parseInt(Math.random()*(n-m))
}


/**
 * 接口请求
 * options 请求信息
 * success 成功返回函数
 * fail 失败返回函数
 */
const appKey = 'u71-WIzWg' // 用了做网关统计的 固定值
const lkRequest = (options, success, fail) => {
    console.log(options)
    let header = {
        'Content-Type': 'application/x-www-form-urlencoded',
        appkey: appKey
    }
    let method = 'POST'
    if (options.contentType) {
        header['Content-Type'] = options.contentType
    }
    if (options.method) {
        method = options.method
    }
    let params = {}
    if (options.params) {
        params = options.params
    }
    wx.request({
        header: header,
        method: method,
        url: options.url,
        dataType: 'json',
        data: params,
        success: success,
        fail: fail
    })
}


export default {
     isRight,
     init,
     isFit,
     dpdConfigApi,
    getTaste,
    getJieQi,
    getLastExamDetails,
    uuid,
    rand,
    lkRequest
  }
